from django.test import TestCase
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
from users.models import User
from .models import File
import os
from typing import Any  # 导入Any类型用于兼容


class FileViewSetTest(TestCase):

    def setUp(self):
        self.client: APIClient = APIClient()  # 明确client类型为APIClient
        # 明确用户类型为User模型
        self.user: User = User.objects.create_user(username='test', password='123', role='user')
        self.admin: User = User.objects.create_user(username='admin', password='123', role='admin')

        # 测试文件路径处理
        self.test_file_path = os.path.join(os.path.dirname(__file__), 'test.png')
        with open(self.test_file_path, 'wb') as f:
            f.write(b'fake image data')

    def test_upload_file(self):
        # 使用Any类型兼容，强制消除类型警告
        self.client.force_authenticate(user=self.user)  # type: ignore[arg-type]

        # 上传文件逻辑
        url = reverse('file-list')
        with open(self.test_file_path, 'rb') as f:
            data = {'name': '测试文件', 'file': f}
            response = self.client.post(url, data, format='multipart')

        # 断言验证
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(File.objects.count(), 1)
        self.assertEqual(File.objects.first().uploaded_by, self.user)

    def tearDown(self):
        if os.path.exists(self.test_file_path):
            os.remove(self.test_file_path)